<?php
// +----------------------------------------------------------------------
// | RXThinkCMF_EVTP5.1_PRO前后端分离旗舰版框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | 作者: ZhangXuanNeng <rxthinkcmf@163.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;

use app\admin\model\BoxGmEcs;
use app\admin\model\BoxGmEs;
use app\admin\model\ChannelOpenServer;
use app\admin\model\ChannelGame;
use app\admin\model\BoxGmRedis;
use think\Db;
use think\Exception;

/**
 * 申请游戏管理-服务类
 * @author steven
 * @since: 2024/01/22
 * Class ChannelService
 * @package app\admin\service
 */
class ChannelOpenServerService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new ChannelOpenServer();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2023/08/07
     * @author steven
     */
    public function getList(): array
    {
        $param = request()->param();
        // 查询条件
        $map = [];
        $id  = isset($param['id']) ? trim($param['id']) : '';
        if ($id) {
            $map[] = ['a.id', '=', $id];
        }
        // 渠道名称
        $name = isset($param['game_name']) ? trim($param['game_name']) : '';
        if ($name) {
            $map[] = ['b.game_name', 'like', "%{$name}%"];
        }
        $is_audit = isset($param['is_audit']) ? trim($param['is_audit']) : '';
        if ($is_audit != '') {
            $map[] = ['a.is_audit', '=', intval($is_audit)];
        }
        // 有效标识
        $mark = isset($param['mark']) ? (int)$param['mark'] : 0;
        if ($mark) {
            $map[] = ['a.mark', '=', $mark];
        }

        $list = $this->model->alias('a')
            ->field('a.*,b.game_name,u.nickname as audit_admin_name')
            ->leftJoin('box_gm_game b', 'a.gm_game_id=b.id')
            ->leftJoin('user u', 'a.audit_admin_id=u.id')
            ->where($map)
            ->order('a.id', 'desc')
            ->paginate(10, false, ['query' => $param])->toArray();
        $arr  = $list['data'] ?? [];
        if (!empty($arr)) {
            $gm_ecs_ids   = array_column($arr, 'gm_ecs_id');
            $gm_es_ids    = array_column($arr, 'gm_es_id');
            $gm_redis_ids = array_column($arr, 'gm_redis_id');

            $ecs_list = BoxGmEcs::where('id', 'in', $gm_ecs_ids)->select()->toArray();
            $ecs_list = array_column($ecs_list, 'ecs_name', 'id');

            $es_list = BoxGmEs::where('id', 'in', $gm_es_ids)->select()->toArray();
            $es_list = array_column($es_list, 'es_name', 'id');

            $redis_list = BoxGmRedis::where('id', 'in', $gm_redis_ids)->select()->toArray();
            $redis_list = array_column($redis_list, 'redis_name', 'id');

            for ($i = 0; $i < count($arr); $i++) {
                $arr[$i]['ecs_name']   = $ecs_list[$arr[$i]['gm_ecs_id']] ?? '暂无';
                $arr[$i]['es_name']    = $es_list[$arr[$i]['gm_es_id']] ?? '暂无';
                $arr[$i]['redis_name'] = $redis_list[$arr[$i]['gm_redis_id']] ?? '暂无';
            }
        }

        //返回结果
        return array(
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $arr,
            "count" => $list['total'],
        );
    }

    public function edit()
    {
        $param = request()->param();
        return parent::newEdit($param, false, true); // TODO: Change the autogenerated stub
    }

    /**
     * Desc : 审核游戏
     * User : you name
     * Date : 2024-01-24 16:52
     * @return array
     */
    public function audit(): array
    {
        Db::startTrans();
        try {
            $param = request()->param();
            if (!in_array($param['is_audit'], [1, 2])) {
                throw new Exception('未选择审核按钮!');
            }
            $updateRes = $this->model->where('id', $param['id'])->update(['is_audit' => $param['is_audit']]);
            if ($updateRes) {
                if ($param['is_audit'] == 1) {  //审核通过
                    //申请成功锁定当前服务器
                    $ecsRes = (new BoxGmEcs())->field('id,status')->where('id', $param['gm_ecs_id'])->find();
                    if ($ecsRes['status'] == 2) {
                        throw new Exception('当前ECS服务器已使用!');
                    } elseif (!$ecsRes) {
                        throw new Exception('当前ECS服务器不存在!');
                    }
                    $esRes = (new BoxGmEs())->field('id,status')->where('id', $param['gm_es_id'])->find();
                    if ($esRes['status'] == 2) {
                        throw new Exception('当前ES服务已使用!');
                    } elseif (!$esRes) {
                        throw new Exception('当前ES服务不存在!');
                    }
                    $redisRes = (new BoxGmRedis())->field('id,status')->where('id', $param['gm_redis_id'])->find();
                    if ($redisRes['status'] == 2) {
                        throw new Exception('当前Redis服务已使用!');
                    } elseif (!$redisRes) {
                        throw new Exception('当前Redis服务不存在!');
                    }

                    if (!empty($param['gm_ecs_id'])) (new BoxGmEcs())->where('id', $param['gm_ecs_id'])->update(['status' => 2, 'gm_game_id' => $param['gm_game_id']]);
                    if (!empty($param['gm_es_id'])) (new BoxGmEs())->where('id', $param['gm_es_id'])->update(['status' => 2, 'gm_game_id' => $param['gm_game_id']]);
                    if (!empty($param['gm_redis_id'])) (new BoxGmRedis())->where('id', $param['gm_redis_id'])->update(['status' => 2, 'gm_game_id' => $param['gm_game_id']]);

                } else {  //审核不通过, 重置资源
                    if (!empty($param['gm_ecs_id'])) (new BoxGmEcs())->where(['id' => $param['gm_ecs_id']])->update(['status' => 0]);
                    if (!empty($param['gm_es_id'])) (new BoxGmEs())->where(['id' => $param['gm_es_id']])->update(['status' => 0]);
                    if (!empty($param['gm_redis_id'])) (new BoxGmRedis())->where(['id' => $param['gm_redis_id']])->update(['status' => 0]);
                }
            }
            Db::commit();
            return message('审核成功!', true);
        } catch (Exception $e) {
            Db::rollback();
            return message($e->getMessage(), false);
        }
    }

    /**
     * Desc : 获取游戏名称
     * User : you name
     * Date : 2024-01-24 17:27
     * @return array
     */
    public function getGameName(): array
    {
        $map        = [
            'mark'   => 1,
            'is_use' => 1
        ];
        $game_names = ChannelGame::where($map)->field('id,game_name')->select();
        return message('获取成功', true, $game_names);
    }


}